using System;
using UnityEngine;

public class CameraAutoFitter : SingletonBehaviour<CameraAutoFitter>
{
    [SerializeField] private Camera targetCamera;
    [SerializeField] private float padding = 1.2f; // 视野边距调整
    public Transform curTarget;
    public Transform targetParent;

    public RenderTexture targetTexture
    {
        get { return targetCamera.targetTexture; }
    }

    public void FitToBounds(Bounds bounds)
    {
        if (targetCamera == null)
            targetCamera = Camera.main;

        // 固定45度俯视角度（X轴旋转45度）
        Quaternion fixedAngle = Quaternion.Euler(45, 0, 0);
        targetCamera.transform.rotation = fixedAngle;

        // 计算包围盒中心点
        Vector3 center = bounds.center;

        // 计算包围盒对角线长度（物体大小）
        float objectSize = bounds.size.magnitude;

        // 计算相机到物体的理想距离
        float distance;
        if (targetCamera.orthographic)
        {
            targetCamera.orthographicSize = objectSize * padding;
            distance = bounds.extents.magnitude * 2f; // 正交相机需要更大距离
        }
        else
        {
            float fovRad = targetCamera.fieldOfView * Mathf.Deg2Rad;
            distance = (objectSize * padding) / Mathf.Tan(fovRad * 0.5f) * 1.5f; // 透视相机增加距离系数
        }

        // 设置相机位置（保持45度俯视）
        Vector3 offset = fixedAngle * Vector3.forward * -distance;
        targetCamera.transform.position = center + offset;
    }

    public Bounds bounds;

    // 示例：加载 Prefab 并适配相机
    public void LoadAndFitModel(GameObject prefab)
    {
        targetParent.eulerAngles = Vector3.zero;
        if (curTarget != null && !curTarget.Equals(null)) GameObject.DestroyImmediate(curTarget.gameObject);
        curTarget = Instantiate(prefab).transform;

        curTarget.localPosition = Vector3.zero;
        ModeifyLayer(curTarget, LayerMask.NameToLayer("PreModel"));
        bounds = CalculateBounds(curTarget);
        curTarget.SetParent(targetParent);
        curTarget.localPosition = -bounds.center;
        FitToBounds(bounds);
    }

    // 计算物体及其子物体的总包围盒
    private Bounds CalculateBounds(Transform obj)
    {
        Renderer[] renderers = obj.GetComponentsInChildren<Renderer>();
        if (renderers.Length == 0)
            return new Bounds(obj.transform.position, Vector3.one);

        Bounds bounds = renderers[0].bounds;
        foreach (Renderer r in renderers)
        {
#if UNITY_EDITOR
            r.sharedMaterial.shader = Shader.Find(r.sharedMaterial.shader.name);
#endif
            bounds.Encapsulate(r.bounds);
        }

        return bounds;
    }

    void ModeifyLayer(Transform tf, int layer)
    {
        tf.gameObject.layer = layer;
        if (tf.childCount > 0)
        {
            for (int i = 0; i < tf.childCount; i++)
            {
                ModeifyLayer(tf.GetChild(i), layer);
            }
        }
    }

    private void OnDrawGizmos()
    {
        if (curTarget != null)
        {
            Gizmos.DrawWireCube(bounds.center+curTarget.transform.position, bounds.size);
        }
    }

    [Header("旋转控制")]
    [SerializeField] private float horizontalSpeed = 180f; // 水平旋转速度
    [SerializeField] private float verticalSpeed = 180f; // 垂直旋转速度
    [SerializeField] private bool invertVertical = true; // 是否反转垂直轴
    [SerializeField] private bool inverthorizontal = true; // 是否反转水平轴
    [SerializeField] private Vector2 min = new Vector2(0.1f, 0.1f);
    private float xRot = 0;
    private float yRot = 0;
    public void Drag(Vector2 _inputValues)
    {
        if (curTarget == null) return;
        // 获取输入值（范围-1到1）
        float x = Mathf.Clamp(_inputValues.x, -1f, 1f);
        float y = Mathf.Clamp(_inputValues.y, -1f, 1f);
        if (Math.Abs(y) < min.y) y = 0;
        if (Math.Abs(x) < min.x) x = 0;

        // 计算旋转量（带速度控制）
         xRot = x * horizontalSpeed * Time.fixedDeltaTime * (inverthorizontal ? -1 : 1);
         yRot = y * verticalSpeed * Time.fixedDeltaTime * (invertVertical ? -1 : 1);


        // 应用旋转（局部坐标系）
        targetParent.Rotate(Vector3.up, xRot, Space.Self); // 水平绕世界Y轴
        targetParent.Rotate(Vector3.right, yRot, Space.World); // 垂直绕自身X轴
    }
}